package com.bruce.log.mdc;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * MDC 线程日志分离设置
 *
 * @author xin.ding
 * @date 2021/5/17 9:52
 */
@Slf4j
public class MdcTest {

    public static void main(String[] args) {
        LogUtils.setLogFile("main.log");

        log.info("Mdc Test Start ...");
        newThreadTest();
        threadPoolTest();

        currentThreadTest();
        LogUtils.setLogFile("main.log");
        log.info("Mdc Test Stop ...");
    }


    private static void threadPoolTest() {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 5; i++) {
            executorService.submit(new Task("task" + i));
        }
    }

    private static void newThreadTest() {
        for (int i = 0; i < 5; i++) {
            new Thread(new Task("task" + i)).start();
        }
    }

    private static void currentThreadTest() {
        LogUtils.setLogFile("sameThread");
        for (int i = 0; i < 5; i++) {
            log.info("{} info", Thread.currentThread().getName());
        }
    }


    static class Task implements Runnable {
        String taskName;

        final Map<String, String> contextMap = LogUtils.getContextMap();

        public Task(String taskName) {
            this.taskName = taskName;
        }

        @Override
        public void run() {
            LogUtils.setContextMap(contextMap);

            for (int i = 0; i < 5; i++) {
                log.debug("{} debug", taskName);
                log.info("{} info", taskName);
                log.warn("{} warn", taskName);
                log.error("{} error", taskName);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }
    }
}
